﻿using System;
using System.Collections.Generic;

namespace ET
{
	[MessageHandler]
	public class C2G_EnterMapHandler : AMRpcHandler<C2G_EnterMap, G2C_EnterMap>
	{
		protected override async ETTask Run(Session session, C2G_EnterMap request, G2C_EnterMap response, Action reply)
		{
			TUser user = session.GetComponent<SessionUserComponent>().User;
			user.LastPlay = request.Index;
			DBComponent db = session.Domain.GetComponent<DBComponent>();
			List<TCharacter> characters = await db.Query<TCharacter>(x => x.UserId == user.Id);

			if(characters.Count < request.Index)
            {
				response.Error = ErrorCode.ERR_Error;
				response.Message = "选择角色错误";
            }

			TCharacter character = characters[request.Index - 1];

			/*BagComponent bag = await DBHelper.GetDBItem<BagComponent>(character.Id);

			character.AddComponent(bag);*/
			session.AddComponent<SessionCharacterComponent>().Character = character;
			character.DBCacheId = StartSceneConfigCategory.Instance.GetBySceneName(session.DomainZone(), Enum.GetName(SceneType.DBCache)).SceneId;

			// 在map服务器上创建战斗Unit
			long mapInstanceId = StartSceneConfigCategory.Instance.GetBySceneName(session.DomainZone(), "Map").SceneId;
			M2G_CreateUnit createUnit = (M2G_CreateUnit)await ActorMessageSenderComponent.Instance.Call(
				mapInstanceId, new G2M_CreateUnit() { CharacterId = character.Id,DBCacheId = character.DBCacheId, GateSessionId = session.InstanceId });

			
			character.UnitId = createUnit.UnitId;
			user.UnitId = createUnit.UnitId;
			await db.Save(user);
			response.UnitId = createUnit.UnitId;
			response.Unit = createUnit.Unit;
			
			reply();
		}
	}
}